<?php
include("siteTop.php");
$documentType = $_GET['documentType'];

    if ($documentType == "MainDocument") {
        $documentTypeFull = "Main Document";
        $thePermissions = array('ROUTEMAIN');
    }
    
    else {
        if ($documentType == "Attachment") {
            $documentTypeFull = "Attachment";
            $thePermissions = array('SENDSUBDOC');
        }
    }
?>
<!-- HEADER START -->
<!--JAVASCRIPT SOURCES-->
    <script src="js/jquery-1.6.2.min.js"></script>

    <!--ACTUAL JS SCRIPTS AND JQUERIES-->
    <script type="text/javascript">
        jQuery(document).ready(function(){ 
            var type = "<?php echo $documentType; ?>";
            // START - CHANGE FIRST THE CSS OF THE NAV BAR
//            jQuery("#tagDoc-nav").addClass("highlightMenuBar");
            
            if( type == 'MainDocument' )
                jQuery("#routeMainDoc-nav").addClass("highlightMenuBar");
            else
                jQuery("#sendSubdoc-nav").addClass("highlightMenuBar");
            // END - CHANGE FIRST THE CSS OF THE NAV BAR

              jQuery("#attachmentHeader").hide();
            // Get all documents
            jQuery.ajax({
                type : 'POST',
                url : 'ajaxRequests/getDocumentListForTag.php',
                dataType : 'json',
                data: {
                    docType : "<?php echo $documentType; ?>"
                },
                success : function(data){
                    jQuery.each(data, function(index, data) {
                        jQuery(".documentList").append("<option value='"+data.documentSetupId+"'>"+data.documentName+"</option>");
                    });
                    
                    // Show available routes for main document
                    <?php 
                        if( $documentType == "MainDocument" ){
                            ?>
                                // Show available document routes from the selected documentId
                                showDocRoutes();                
                            <?php
                        }
                    ?>
                },
                error : function() {
                    alert("fail");
                }
            }); // END - displays all documents in document name


            // START - JQUERY TO CHECK IF DOCUMENT ID ALREADY EXISTS
            jQuery("#documentId").blur(function(){
                if (this.value != "") {
                                   
                    jQuery.ajax({
                        type : 'POST',
                        url : 'ajaxRequests/checkDocumentId.php',
                        dataType : 'json',
                        data: {
                            docId : jQuery("#documentId").val(),
                            docType : jQuery("#documentType").val()
                        },
                        success : function(data){
                            jQuery(".errorMessage").html("");
                            jQuery(".successMessage").html("");
                            
                            if (data.idExist == "1") {
                                 jQuery(".errorMessage").html("Document ID already exist.");
                                 jQuery("#documentId").val("");
                                 jQuery("#documentId").focus();
                            }
                            else{
                                flagSame =0;
                                jQuery(".documentId").each( function(){
                                   if(this.value == jQuery("#documentId").val()){
                                       flagSame++;
                                   }
                                });
                                if (flagSame>1){
                                 jQuery(".errorMessage").html("Document ID already exist.");
                                 jQuery("#documentId").val("");
                                 jQuery("#documentId").focus();
                                }
                            }
                                            
                           
  
                        },
                        error : function() {
                            alert("fail");
                        }
                    }); 
                } // END of IF
                
                else {
                    jQuery(".successMessage").html("");
                }
            }); // END - JQUERY TO CHECK IF DOCUMENT ID ALREADY EXISTS
            
            // START - CHANGE DISPLAYED DOCUMENT ROUTES WHEN USER CHANGES THE DOCUMENT NAME
           if( type == 'MainDocument' ) {
             jQuery("#documentName").change(function(){
                showDocRoutes();
                removeAllAttachments();
             }); // CHANGE DISPLAYED DOCUMENT ROUTES WHEN USER CHANGES THE DOCUMENT NAME
            
           }
            
            
            // ~~~~~~~~~~~FUNCTIONS LIST~~~~~~~~~~~~~~~~~~~~~~~
            
            
            // START - DISPLAY AVAILABLE DOCUMENT ROUTES FOR THE CHOSEND DOCUMENT SETUP ID
            function showDocRoutes(){
                var documentSetupId;
                
                jQuery.ajax({
                    type : 'POST',
                    url : 'ajaxRequests/getDocumentRoutes.php',
                    dataType : 'json',
                    data: {
                        documentSetupId : jQuery("#documentName").val()
                    },
                    success : function(data){
                        // REMOVE THE CHILDREN OF documentRoute DROPDOWN
                        jQuery("#documentRoute").children().remove();
                        
                        // APPEND DOCUMENT ROUTES AVAILABLE FOR documentSetupId
                        jQuery.each(data, function(index, data) {
                            jQuery(".documentRouteList").append("<option value='"+data.routeId+"'>"+data.routeName+"</option>");
                        });
                        
                        // JQUERY-AJAX TO GET ALL REQUIRED ATTACHMENTS.
                        showRequiredAttachments();
                        
                    },
                    error : function() {
                        alert("Error in getting the available document routes.");
                    }
                });
            } // END - DISPLAY AVAILABLE DOCUMENT ROUTES FOR THE CHOSEND DOCUMENT SETUP ID
            
            // Start - Update required attachments when the document route was change
            jQuery('#documentRoute').live('change',function(){
                showRequiredAttachments();
                removeAllAttachments();
            }); // End - Update required attachments when the document route was change
            
            function showRequiredAttachments(){
                jQuery.ajax({
                    type : 'POST',
                    url : 'ajaxRequests/getRequiredAttachments.php',
                    dataType : 'json',
                    data: {
                        routeId : jQuery(".documentRouteList").val(),
                        stepNumber : 1,
                        subRouteId : "NULL"
                    },
                    success : function(data){
                        if (data.documentName != "none") {
                            jQuery("#reqdAttachments").children().remove();
                            currentDiv = "";
                            
                            jQuery.each(data, function(index, data) {
                              jQuery("#reqdAttachments").append("<div style='margin-bottom:2%;'>" + data.documentName +" <input style='margin-right:30%;float:right;font-size:10px; padding-right: 1px;padding-left: 1px;padding-top: 1px;padding-bottom: 1px;' type='button' class='requiredAttachmentsClass siteGreenButton addAttachmentButton' title='"+data.documentName+"' value='Add' id='"+data.documentSetupId+"'</div>");
                                
                            });
                            
                            //jQuery("#reqdAttachments").html(currentDiv);
                        }
                        
                        else {
                            jQuery("#reqdAttachments").html("No required attachments.");
                        }
                                                  
                    },
                    error : function() {
                        alert("Error in getting the available document routes.");
                    }
                });
            } // END - DISPLAY AVAILABLE DOCUMENT ROUTES FOR THE CHOSEND DOCUMENT SETUP ID
         
         
            jQuery("#submitForm").submit(function() {
                
                 documentTags = jQuery("#documentTags").val().split(',');
                 documentID= jQuery("#documentId").val();

                 Message = "Successfully Routed "+documentID+" ("+ documentTags[0]+")";
                
                jQuery("#successMessages").val(Message);

                
                
                    
            });
            
            
            // FOR SEND ATTACHMENT BUTTON
            jQuery("#tagButton").live("click",function () {
             
                flag=1;
                jQuery(".required").each(function(){
                   if(jQuery(this).val() == ''){
                     flag = 0;
                   }    
                });  
                
                if (flag){    
                     jQuery.ajax({
                            type : 'POST',
                            url : 'ajaxRequests/tagAttachmentAjax.php',
                            dataType : 'json',
                            data: {
                                documentName: jQuery("#documentName").val(),
                                documentId: jQuery("#documentId").val(),
                                departmentId: jQuery("#departmentId").val(),
                                positionId: jQuery("#positionId").val(),
                                documentTags : jQuery("#documentTags").val(),
                                location : "<?php echo $userId ?>"

                            } , success  : function (data){

                                jQuery("#submitForm").submit();
                            },  error : function(){

                                alert("error ajax in tagattachmentajax");
                            }


                       });
              
                }
                else{
                alert("Please input all information.");
                }
            });
            
            //FOR ROUTE MAINDOCUMENT BUTTON 
            jQuery("#routeButton").click(function() {
              flag = 1;
             attachmentName="";
             alertString="";
              jQuery('.attachmentName').each( function(){
                 attachmentName = attachmentName +","+ jQuery(this).val();
              });
              attachmentId="";
             
              jQuery('.attachmentId').each( function(){
                 attachmentId = attachmentId +","+ jQuery(this).val();
              });
             
             
              
              jQuery(".requiredAttachmentsClass").each(function(){
                  if(jQuery(this).is(":visible")){
                      alertString+="Please Add a "+ jQuery(this).attr("title") +"\n";
                      flag = 0;
                      
                  }
                  
                  });
              
              jQuery(".required").each(function(){
                 if(jQuery(this).val() == ''){
                     flag = 2;
                 }    
              });    
                  
                  
                  
                  if(flag==1){
                      
                      
                    jQuery.ajax({
                        type : 'POST',
                        url : 'ajaxRequests/routeDocumentAjax.php',
                        dataType : 'json',
                        data: {
                            documentName: jQuery("#documentName").val(),
                            documentId: jQuery("#documentId").val(),
                            currentRoute: jQuery("#documentRoute").val(),
                            documentTags: jQuery("#documentTags").val(),
                            attachmentName : attachmentName,
                            attachmentId : attachmentId,
                            location : "<?php echo $userId ?>"
                        } , success : function(data){
                            
                            jQuery("#submitForm").submit();
                            
                        }, error : function()
                        {
                            alert("Error ajax in Route Document");
                        }


                   });
                      
                  }
                  else if (flag==2){
                     alertString+='Please input all information.\n';
                  }
                  

              
                if(flag!=1){
                   alert(alertString);
                }
              
            });
            
            // remove attachment JQUERY
            
            jQuery(".removeButton").live("click", function() {  
                x = 0;
                removeId= jQuery(this).attr('title');
                jQuery(this).parent().parent().remove();
                
                jQuery("."+removeId).each(function(){
                    x++;
                });
                
                if(x==0){

                    
                        jQuery("#"+removeId).show();
                        jQuery("#"+removeId).parent().children(":first-child").remove();
                    

                    if(jQuery("#attachmentHeader").next().attr('id')=='attachmentFooter'){
                        jQuery("#attachmentHeader").hide();
                    }
                }
            });
            
            
            // ADD ATTACHMENT JQUERY
            jQuery(".addAttachmentButton").live("click",function() {
                // add transparent box and content box
                jQuery(".body").prepend("<div class='theatreTransparent'> </div>");
                jQuery(".body").prepend("<div class='theatreContentBox'> </div>");               
               
                //add contents of the popup
                documentNameId= jQuery(this).attr('id');
                documentNameTitle= jQuery(this).attr('title');
                
                jQuery(".theatreContentBox").append("<div class='theatreContent'><h1>Add Attachment </h1> <br> <span class='screenlet'>Attachment Information</span> </div>");
                jQuery(".theatreContent").append("<table><tr><td>Document Name</td><td id='documentName'> " +
                                             
                    "</td></tr> <tr><td>Document ID</td><td> <input type='text' id='theatreId' class='documentId'> </td><td>  <span id='errorMessage' class='errorMessage'></span> <span id='successMessage'class='successMessage'></span></td></tr>  </table>");
                jQuery(".theatreContent").append("<input type='button' id='theatreButton' value='Add' class='siteGreenButton'> <input type='button' id='cancelButton' value='Cancel' class='siteGreenButton'>  ");
                
                if(documentNameId=="addAttachmentButton")
                {
                   jQuery("#documentName").append("<select value='namedropdown' id='theatreName' class='documentList'> </select>");
                  // get document name in theatre
                    jQuery.ajax({
                        type : 'POST',
                        url : 'ajaxRequests/getDocumentList.php',
                        dataType : 'json',
                        data: {
                            docType : "Attachment"
                        },
                        success : function(data){
                            jQuery.each(data, function(index, data) {
                                jQuery("#theatreName").append("<option value='"+data.documentSetupId+"'>"+data.documentName+"</option>");
                            });                        
                        },
                        error : function() {
                            alert("fail ajax get document name in theatre");
                        }
                    }); // END - displays all documents in document name
                }
                else
                {
                 jQuery("#documentName").append("<input type='hidden' id='theatreName' value='"+documentNameId+"'> <div>"+documentNameTitle+" </div>");
                }
                jQuery("#theatreId").focus();
                // THEATREID ON BLUR
                jQuery("#theatreId").live("blur",function() {
                if (this.value != "") {        
                    jQuery.ajax({
                        type : 'POST',
                        url : 'ajaxRequests/checkDocumentId.php',
                        dataType : 'json',
                        data: {
                            docId : jQuery("#theatreId").val(),
                            docType : "Attachment"
                            },
                            success : function(data){
                                jQuery("#errorMessage").html("");
                                jQuery("#successMessage").html("");

                                if (data.idExist == "1") {
                                     jQuery("#errorMessage").html("Document ID already exist.");
                                     jQuery("#theatreId").val("");
                                }
                                else{
                                flagSame =0;
                                
                                jQuery(".documentId").each( function(){
                                   if(this.value == jQuery("#theatreId").val()){
                                       flagSame++;
                                   }
                                });
                                if (flagSame>1){
                                 jQuery("#errorMessage").html("Document ID already exist.");
                                     jQuery("#theatreId").val("");
                                     jQuery("#theatreId").focus();
                                }
                            }

                             

                            },
                            error : function() {
                                alert("fail ajax on blur theatreID");
                            }
                        }); 
                    } // END of IF

                    else {
                        jQuery("#successMessage").html("");
                        jQuery("#errorMessage").html("");
                    }
                }); // END - THEATRE ON BLUR
                
                // ADD BUTTON to RETURN THE VALUES TO FORM
               jQuery("#cancelButton").click(function(){
                    jQuery(".theatreTransparent").click();
                });
                
               jQuery("#theatreButton").click(function(){
                   theatreId = jQuery("#theatreId").val();
                   theatreName = jQuery("#theatreName").val();
                   
                   theatreLabel = jQuery("#theatreLabels").val();
                   
                   
                   
                   if( theatreId == ""){
                       alert("Please input the Attachment ID.");
                   }
                   else{  
                       if(documentNameId == "addAttachmentButton"){
                        theatreActualName= jQuery("#theatreName option:selected").text();
                        documentNameId = jQuery("#theatreName option:selected").val();
                       }
                       else {
                           theatreActualName = documentNameTitle;
                       }
                       jQuery("#attachmentFooter").before("<tr>"+
                            "<td>"+ theatreId +" <input name='attachmentId' type='hidden' class='attachmentId documentId' value='"+ theatreId +"'></td>"+
                            "<td>"+ theatreActualName +" <input name='attachmentName' class='attachmentName "+documentNameId +"' type='hidden' value='"+ documentNameId +"'></td> "+
                            "<td><input type='button' title='"+documentNameId+"' value='Remove' class='removeButton siteRedButton'></td> "+
                            "</tr>"
                       );
                       jQuery("#attachmentHeader").show();
                     
                       if (documentNameId != "addAttachmentButton"){
                           
                           if(jQuery("#"+documentNameId).is(":visible")){
                               
                               jQuery("#"+documentNameId).hide();
                               jQuery("#"+documentNameId).before("<image style='float:right;margin-right:40%;width:5%;height:5%;' src='images/checkmark.png'>");
                           }
                       }
                       jQuery(".theatreTransparent").click();
                   }
                }); // RETURN VALUES

            }); //END  - ADD ATTACHEMENT JQUERY
            
            // on click outside the content box
            
            
            jQuery(".theatreTransparent").live("click",function() {
                jQuery(".theatreTransparent").remove();
                jQuery(".theatreContentBox").remove();
            });  
            
            
            
            if (type=="Attachment"){
                jQuery.ajax({
                    type : 'POST',
                    url : 'ajaxRequests/getDepartmentList.php',
                    dataType : 'json',
                    data: {
                        
                    },
                    success : function(data){
                        jQuery.each(data, function(index, data) {
                            jQuery("#departmentId").append("<option value='"+data.departmentId+"'>"+data.departmentName+"</option>");
                        });
                        jQuery.ajax({
                            type : 'POST',
                            url : 'ajaxRequests/getPositions.php',
                            dataType : 'json',
                            data: {
                                    departmentId : jQuery("#departmentId").val()
                            },
                            success : function(data){
                                jQuery.each(data, function(index, data) {
                                    jQuery("#positionId").append("<option value='"+data.positionId+"'>"+data.positionName+"</option>");
                                });

                            },
                            error : function() {
                                alert("fail ajax getpositionList.php");
                            }
                    });
                    },
                    error : function() {
                        alert("fail ajax getdepartmentList.php");
                    }
                });
                
                
                
                jQuery("#departmentId").change(function(){
                    jQuery("#positionId").empty();
                    
                    jQuery.ajax({
                        type : 'POST',
                        url : 'ajaxRequests/getPositions.php',
                        dataType : 'json',
                        data: {
                                departmentId : jQuery(this).val()
                        },
                        success : function(data){
                            jQuery.each(data, function(index, data) {
                                jQuery("#positionId").append("<option value='"+data.positionId+"'>"+data.positionName+"</option>");
                            });

                        },
                        error : function() {
                            alert("fail ajax getpositionList.php");
                        }
                    });
                });
                
            }
            
            
            
        }); // END - (DOCUMENT READY FUNCTION)
        
        function removeAllAttachments(){
            jQuery(".removeButton").each(function(){
                jQuery(this).parent().parent().remove();
                
            });
            jQuery("#attachmentHeader").hide();
        }
        
    </script>
    <!-- HEAD END -->
<?php include("siteMiddle.php"); ?>

    <div id="content" >

        <h1>
            <?php 
            if ( $documentTypeFull == 'Main Document' ) 
                echo "Route Document";
            else
                echo "Send Document";
            ?> 
        
        </h1>
        
        <?php
        // Check permission
        if ( checkPermission( $thePermissions, $userId ) == true ) {
        ?>
        
        <form id="submitForm" name="submitForm" method="post" action="dashboard.php">
             <span class="screenlet" >Document Information</span>
             <input type="hidden" id="successMessages" name="successMessages">
            <table>
                <tr><td>Document Type <input type="hidden" name="userLogged" value="<?php echo $userId?>"></td>
                    <td>
                        
                        <!--IDENTIFY IF DOC TYPE = MAIN DOCUMENT / ATTACHMENT-->
                        <?php
                        echo $documentTypeFull;
                        ?>
                        <input type="hidden" name="documentType" id="documentType" value="<?php echo $documentType?>">
                    </td><td></td>
                </tr>

                <tr><td>Document Name</td>
                    <td>
                        <select value="namedropdown" name="documentName" id="documentName" class="documentList">                         
                        </select>
                    </td><td></td>
                </tr>

    <!-- If Document type = Main Document, show Document Route-->
    <?php if ($documentType == "MainDocument") { ?>
                    <tr><td>Document Route</td>
                        <td>
                           
                            <select  name="documentRoute" id="documentRoute" class="documentRouteList">                         
                            </select>
                        </td><td></td>
                    </tr>
    <?php } ?>

                <tr><td>Document ID</td>
                    <td>
                        <input type="text" value="" class="required documentId" name="documentId" id="documentId"/>
                    </td>
                    <td>
                        <span class="errorMessage"></span>
                        <span class="successMessage"></span>
                    </td>
                </tr>

                <tr>
                    <td>Document Label</td>
                    <td>
                        <input type="text" value="" class="required" id="documentTags" name="documentTags"/>
                    </td><td></td>
                </tr>
                <tr>
                    <td>
                        
                    </td>
                    <td>
                        <i style="font-size:12px;">(Note: Separate multiple labels by commas. <br> The first tag will serve as the Main tag.   )</i>
                    </td>
                </tr>

                
    <?php if ($documentType == "Attachment") {?>
        
         <tr>
             <td>Department</td>
             <td>
                 <select id="departmentId" >
                     
                 </select>
             </td><td></td>
         </tr>
         <tr>
             <td>Position</td>
             <td>
                 <select id="positionId">
                     
                 </select>
             </td><td></td>
         </tr>
        
    <?php }?>
                
                
            </table>

    <?php if ($documentType == "MainDocument") { ?>
                
                <span class="screenlet" >Attachments</span>
                <table style ="width:50%;" border="1" name="attachmentsTable" id="attachmentsTable">
                    <tr>
                        <td colspan="4">
                            <b><u>Required Attachments :</u></b> 
                            <div id="reqdAttachments"></div>
                            <br>
                            <hr style="margin-bottom:2%;">
                            
                            <div style="margin-bottom:2%;"> Others: <input type="button" style='margin-right:40%;float:right;font-size:10px; padding-right: 1px;padding-left: 1px;padding-top: 1px;padding-bottom: 1px;' class ="siteGreenButton addAttachmentButton" id="addAttachmentButton" value="Add"></div>
                        </td>
                        
                    </tr>
                    <tr id="attachmentHeader">
                        <th>Document ID</th>
                        <th>Name</th>
                        <th> Action </th>
                    </tr>
                    
                     <tr id="attachmentFooter">
                        
                    </tr>
                    
                    
                </table>
                
    <?php }  ?>



        <!-- IDENTIFY THE BUTTON IF ROUTE (MD) OR TAG (ATTACHMENT)-->
        <?php if ($documentType == "MainDocument") { ?>
            <input type="button" name="routeButton" id="routeButton" value="Route" class="siteGreenButton" />
        <?php } else { if ($documentType == "Attachment") { ?>    
            <input type="button" name="tagButton" id="tagButton" value="Send" class="siteGreenButton"/>
        <?php } } ?>
        </form>

        <?php
        }
        else {
            echo "<div class='noPermissionMsgBox noPermissionMsg' style='border: 2px solid red'><div id='noPermissionMsgs'>You have no permission to view this page.</div></div>";
        }
        // End checking permission
        ?>
    </div>

<?php include ("siteBottom.php"); ?>